package cn.wolfcode.service.Impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.NoticeQueryObject;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;

    @Autowired
    private EmployeeMapper employeeMapper;


    @Override
    public void save(Notice notice) {
        notice.setReadstatus(false);
        notice.setReleasestatus(false);
        notice.setEmployee(UserContext.getCurrentUser());
        notice.setCreattime(new Date());
        noticeMapper.insert(notice);
        noticeMapper.insertRelation(UserContext.getCurrentUser().getId(),notice.getId());
    }

    @Override
    public void delete(Long id) {
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(NoticeQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo, UserContext.getCurrentUser()); //里面不需要自己写limit
        return new PageInfo<Notice>(notices);
    }

    @Override
    public void publish(Long id, Boolean status) {
        noticeMapper.publish(id,status);
        //修改发布状态
        if (status){
            List<Employee> employees = employeeMapper.selectAll();
            noticeMapper.deleteRelation(UserContext.getCurrentUser().getId(),id);
            for (Employee employee : employees) {
                noticeMapper.insertRelation(id,employee.getId());
            }
        }else {
            //取消发布
            noticeMapper.deleteRelation2(id);
            noticeMapper.insertRelation(UserContext.getCurrentUser().getId(),id);
        }
    }

    @Override
    public List<Notice> selectReadNoticeByEmpId(Long eid) {
        List<Notice> notices = noticeMapper.selectReadNoticeByEmpId(eid);
        return notices;
    }

    @Override
    public int selectReadNoticesCount(Long id) {
        return noticeMapper.selectReadNoticesCount(id);
    }


}
